package com.seqb.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

/**
 * @author lilinshen
 * @title 请填写标题
 * @description 请填写相关描述
 * @date 2019/12/24
 */
@Slf4j
public class JwtUtils {

    /**
     * JWT验证过期时间（3个小时）
     */
    private static final long EXPIRE_TIME = 180 * 60 * 1000;
    private static final long EXPIRE_TIME_DOUBLE = 2 * 180 * 60 * 1000;
    //private static final long EXPIRE_TIME = 20 * 1000;
    //private static final long EXPIRE_TIME_DOUBLE = 2 * 20 * 1000;

    /**
     * 校验token是否正确
     *
     * @param token    密钥
     * @param account  账号
     * @param password 密码
     * @return
     */
    public static int verify(String token, String account, String password) {
        try {
            //根据密码生成jwt效验器
            Algorithm algorithm = Algorithm.HMAC256(password);
            JWTVerifier verifier = JWT.require(algorithm).withClaim("account", account).build();
            //效验token
            verifier.verify(token);
            return 1;
        } catch (Exception e) {
            if (e.getMessage().indexOf("expired") > 0) {
                //token超时
                return 2;
            } else if (e.getMessage().indexOf("Signature") > 0) {
                //账号或密码错误
                return 3;
            }
            return 4;
        }
    }

    /**
     * 获得token中的account信息
     */
    public static String getAccount(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("account").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 获得token中的expired信息
     */
    public static Long getExpired(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("expired").asLong();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 生成token签名,180分钟后过期
     *
     * @param account  账号
     * @param password 密码
     * @return token
     */
    public static String sign(String account, String password) {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(password);
        // 附带account和expired信息
        return JWT.create().withClaim("account", account)
                .withClaim("expired", System.currentTimeMillis() + EXPIRE_TIME_DOUBLE)
                .withExpiresAt(date)
                .sign(algorithm);
    }

    public static void main(String[] args) {
        /**
         * 测试生成一个token
         */
        String sign = sign("admin", "4e4c1c9eb048cb321f906287ccc3827a");
        log.warn("测试生成一个token\n" + sign);
    }


}
